# -*- coding: utf-8 -*-

"""
  @author: tangliqi
  @date: 2023/8/1 18:03
  @python version: 3.6 
  @contact me: 110
  ---------------------------------------
  @desc: django-vue-learn => middleware.py
"""
import json

from django.contrib.auth.models import AnonymousUser
from django.middleware.common import MiddlewareMixin

from api_audit.utils.request import get_request_ip, get_request_data, get_request_path, get_request_user, get_os, \
    get_browser
from api_audit.models import OperationLog


class ApiLoggingMiddleware(MiddlewareMixin):
    """
    用于记录API访问日志中间件
    """

    def __init__(self, get_response=None):
        super().__init__(get_response)
        # self.enable = getattr(settings, 'API_LOG_ENABLE', None) or False
        # self.methods = getattr(settings, 'API_LOG_METHODS', None) or set()
        # self.operation_log_id = None

    @classmethod
    def __handle_request(cls, request):
        request.request_ip = get_request_ip(request)
        request.request_data = get_request_data(request)
        request.request_path = get_request_path(request)

    def __handle_response(self, request, response):
        # request_data,request_ip由PermissionInterfaceMiddleware中间件中添加的属性
        body = getattr(request, 'request_data', {})
        # 请求含有password则用*替换掉(暂时先用于所有接口的password请求参数)
        if isinstance(body, dict) and body.get('password', ''):
            body['password'] = '*' * len(body['password'])
        if not hasattr(response, 'data') or not isinstance(response.data, dict):
            response.data = {}
        try:
            if not response.data and response.content:
                content = json.loads(response.content.decode())
                response.data = content if isinstance(content, dict) else {}
        except Exception:
            return
        user = get_request_user(request)
        code = self.get_response_code(response)
        info = {
            'request_ip': getattr(request, 'request_ip', 'unknown'),
            'creator': user if not isinstance(user, AnonymousUser) else None,
            'dept_belong_id': getattr(request.user, 'dept_id', None),
            'request_method': request.method,
            'request_path': request.request_path,
            'request_body': body,
            'response_code': code,
            'request_os': get_os(request),
            'request_browser': get_browser(request),
            'request_msg': request.session.get('request_msg'),
            'status': True if code in [200, 201, 203, 204] else False,
            'json_result': {"code": code, "msg": response.data.get('msg')},
        }

        OperationLog.objects.create(**info)

    def get_response_code(self, response):
        """
        可以自定义返回的code，默认为response.status_code
        """
        code = getattr(response, "status_code", None)

        return code

    def process_request(self, request):
        self.__handle_request(request)

    def process_response(self, request, response):
        """
        主要请求处理完之后记录
        :param request:
        :param response:
        :return:
        """
        # if self.enable:
        #     if self.methods == 'ALL' or request.method in self.methods:
        #         self.__handle_response(request, response)
        self.__handle_response(request, response)
        return response
